package com.ruoyi.management.service.impl;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.management.base.config.AmmeterMessageConstants;
import com.ruoyi.management.base.utils.Crc16Utils;
import com.ruoyi.management.base.utils.DateUtils;
import com.ruoyi.management.base.utils.HexUtils;
import com.ruoyi.management.dao.mapper.AmmeterMapper;
import com.ruoyi.management.dao.mapper.BillingMapper;
import com.ruoyi.management.mqtt.MqttContext;
import com.ruoyi.management.mqtt.MqttProducer;
import com.ruoyi.management.pojo.entity.Qldbykhmx;
import com.ruoyi.management.pojo.param.AmmeterParam;
import com.ruoyi.management.pojo.param.StartAssociationParam;
import com.ruoyi.management.pojo.param.TidParam;
import com.ruoyi.management.pojo.param.ZtParam;
import com.ruoyi.management.pojo.po.*;
import com.ruoyi.management.pojo.vo.*;
import com.ruoyi.management.service.AmmeterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.util.*;


@Slf4j
@Service
public class AmmeterImpl implements AmmeterService {

    @Autowired
    private MqttProducer mqttProducer;
    @Autowired
    private AmmeterMapper ammeterMapper;
    @Autowired
    private BillingMapper billingMapper;
    @Autowired
    private AmmeterTaskImpl ammeterTask;
    @Autowired
    private MqttContext mqttContext;
    @Autowired
    private AmmeterService ammeterService;

    @Override
    public int selectzl(ZtParam ztParam) {
        log.debug("添加智联器");
        ZlPO zlPO=new ZlPO();
        zlPO.setZt(ztParam.getZt());
        zlPO.setLc(ztParam.getLc());
        zlPO.setLocation(ztParam.getLocation());
        zlPO.setZlid(ztParam.getZlid());
        zlPO.setModel(ztParam.getModel());
        zlPO.setPtopic(ztParam.getPtopic());
        zlPO.setStopic(ztParam.getStopic());
        zlPO.setZlid(ztParam.getZlid());
        int i = ammeterMapper.insertzl(zlPO);
        return i;
    }

    @Override
    public List<ZlVO> selectAllZt(ZtParam ztParam) {
        log.debug("查询所有智联器供添加列表选择");
        // 查询登陆的账号拥有的载体项目
        List<ZTVO> ztvos = ammeterMapper.selectZtByNra(ztParam);
        if (CollectionUtils.isNotEmpty(ztvos)) {
            ztParam.setZt(ztvos.get(0).getNr());
        }
        List<ZlVO> zts = ammeterMapper.selectAllZt(ztParam);
        return zts;
    }

    @Override
    public int addZt(ZtParam ztParam) {
        if (ztParam == null) {
            throw new IllegalArgumentException("ZtParam must not be null");
        }
        ZtPo ztPo=new ZtPo();
        ztPo.setNr(Optional.ofNullable(ztParam.getNr()).orElse(""));
        ztPo.setNra(Optional.ofNullable(ztParam.getNra()).orElse(""));
        ztPo.setQygs(Optional.ofNullable(ztParam.getQygs()).orElse(""));
        ztPo.setQybs(ztParam.getQybs());
        ztPo.setGs(ztParam.getGs());
        ztPo.setYxa(ztParam.getYxa());
        ztPo.setYxb(ztParam.getYxb());
        ztPo.setLxbh(1);
        ztPo.setDlb(ztParam.getDlb());
        ztPo.setSslb("载体项目");
        ztPo.setYx(1);
        ztPo.setSkr(ztParam.getSkr());
        ztPo.setKhh(ztParam.getKhh());
        ztPo.setRmbzh(ztParam.getRmbzh());
        ztPo.setDflx(ztParam.getDflx());
        int number=ammeterMapper.selectPxbh();
        ztPo.setPxbh(number+1);
        int i = ammeterMapper.addZt(ztPo);
        //在qldbykhmx表中增加载体字典
        Qldbykhmx record = new Qldbykhmx();
        record.setZt(ztParam.getNr());
        record.setQymc("标识");
        record.setKhbh("连接表 qldbcode");
        record.setKhbha("");
        record.setDbyt("");
        record.setNf(0);
        record.setYf(0);
        record.setHkbz("");
        record.setTname("admin");
        Boolean a = ammeterMapper.insertkh(record);
        return i;
    }

    @Override
    public int updateZt(ZtParam ztParam) {
        ZtPo ztPo=new ZtPo();
        ztPo.setNr(ztParam.getNr());
        ztPo.setNra(ztParam.getNra());
        ztPo.setQygs(ztParam.getQygs());
        ztPo.setQybs(ztParam.getQybs());
        ztPo.setGs(ztParam.getGs());
        ztPo.setYxa(ztParam.getYxa());
        ztPo.setYxb(ztParam.getYxb());
        ztPo.setLxbh(1);
        ztPo.setDlb(ztParam.getDlb());
        ztPo.setSslb("载体项目");
        ztPo.setYx(ztParam.getYx());
        ztPo.setPxbh(ztParam.getPxbh());
        ztPo.setSkr(ztParam.getSkr());
        ztPo.setKhh(ztParam.getKhh());
        ztPo.setRmbzh(ztParam.getRmbzh());
        ztPo.setDflx(ztParam.getDflx());
        int i = ammeterMapper.updateZt(ztPo);
        return i;
    }

    @Override
    public List<AmmeterResultVO> selectAllAmmeter(String dbbh, String zlid, String zt) {
        if (dbbh!=null && zlid!=null){
            return ammeterMapper.selectAllAmmeter(dbbh,zlid, zt);
        }
        if (dbbh==null && zlid!=null){
            return ammeterMapper.selectAllAmmeter2(zlid, zt);
        }
        if (dbbh!=null && zlid==null){
            return ammeterMapper.selectAllAmmeter3(dbbh, zt);
        }
        return ammeterMapper.selectAllAmmeter1(zt);
    }

    @Override
    public ZlVO selectztx(String zlid) {
        return ammeterMapper.selectZlx(zlid);
    }

    @Override
    public List<AmmeterResultVO> selectzldb(String zlid) {
        return ammeterMapper.selectzldb(zlid);
    }

    @Override
    public AmmeterXQVO selectAmmeterx(String dbbh) {
        return ammeterMapper.selectAmmeterx(dbbh);
    }

    @Override
    /**
     * 获取指定电表最接近当前时间的数据
     * @param dbbh 电表编号
     * @return 最接近当前时间的数据，如果无数据则返回 null
     */
    public AmmeterResultPo getClosestAmmeterData(String dbbh) {
        try {
            // 1. 构建 Redis key 模式（假设 key 格式是 "ammeter:result:{dbbh}:*"）
            String redisKeyPattern = "ammeter:result:" + dbbh + ":*";

            // 2. 扫描 Redis 获取该电表的所有 key
            ScanOptions options = ScanOptions.scanOptions().match(redisKeyPattern).build();
            Cursor<byte[]> scan = mqttContext.getRedisTemplate()
                    .getConnectionFactory()
                    .getConnection()
                    .scan(options);

            List<AmmeterResultPo> ammeterDataList = new ArrayList<>();

            // 3. 遍历并获取所有数据
            while (scan.hasNext()) {
                String redisKey = new String(scan.next());
                AmmeterResultPo data = mqttContext.getRedisTemplate().opsForValue().get(redisKey);
                if (data != null) {
                    ammeterDataList.add(data);
                }
            }

            // 4. 关闭游标（重要！避免资源泄漏）
            scan.close();

            // 5. 如果没有数据，返回 null
            if (ammeterDataList.isEmpty()) {
                log.warn("电表 {} 无数据", dbbh);
                return null;
            }

            // 6. 计算最接近当前时间的数据
            long now = System.currentTimeMillis();
            return ammeterDataList.stream()
                    .min(Comparator.comparingLong(po -> Math.abs(po.getTimestamp().getTime() - now)))
                    .orElse(null);
        } catch (Exception e) {
            log.error("获取数据失败: {}", e.toString());
            return null;
        }
    }

    @Override
    public BigDecimal selectSelfPower(String month, String zt, String lc) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        String dbzt="自用";
        List<AmmeterResultVO> dbbhs=ammeterMapper.selectAllDbbh(zt,lc,dbzt);
        BigDecimal selfPower = BigDecimal.ZERO;
        for(AmmeterResultVO dbbh:dbbhs){
            BigDecimal power = ammeterMapper.selectAllPower(date,dbbh.getDbbh());
            power = power.multiply(dbbh.getMagnification());
            selfPower = selfPower.add(power);
        }
        return selfPower;
    }

    @Override
    public DbkhhkbVO selectProjectPower(String month, String zt) {
        Date date=DateUtils.getFirstDayOfMonth( month);
        return ammeterMapper.selectProjectPower(date,zt);
    }

    @Override
    public List<DbkhhsjbVO> selectTenantPower1(String qymc, String zt) {
        return ammeterMapper.selectTenantPower1(qymc,zt);
    }

    @Override
    public Boolean startPower(String dbbh, BigDecimal dbz, Date timestamp) {
        Boolean a=ammeterMapper.startPower(dbbh,dbz,timestamp);
        return a;
    }

    @Override
    public Boolean updateYt(String dbbh, String dbyt) {
        Boolean a=ammeterMapper.updateYt(dbbh,dbyt);
        return a;
    }


    @Override
    public List<DbysyVO> selectMeterList(String date, String tgszt,Integer yxa,String zt) {

        String[] values = tgszt.split(",");// 按照逗号进行分割

        Date lastMonthFirstDay= DateUtils.getFirstDayOfMonth(date);
        return ammeterMapper.selectMeterList(lastMonthFirstDay,values,yxa,zt);
    }

    @Override
    public Boolean switchAmmeter(String dbbh,Integer tNumber) {
        TidParam tidParam=ammeterMapper.selectTidSwitch(dbbh);
        String tid = Integer.toHexString(tidParam.getTid());
        if (tNumber==0){
            //拉闸操作
            byte[] crcHexString = Crc16Utils.getData(tid,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_1,
                    AmmeterMessageConstants.AMMETER_PUBLISH_NULL,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_2,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_3,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_3);
            log.debug("CRC效验码（十六进制）: {}", crcHexString);
            // 将CRC校验码转换为十六进制字符串并转换为大写
            String finalMessageHex = Crc16Utils.byteTo16String(crcHexString).toUpperCase();
            log.info("最终消息（十六进制）: {}", finalMessageHex);
            try {
                byte[] payload = HexUtils.HexStringToByte(finalMessageHex);
                log.debug("最终消息（十六进制）: {}", payload);
                // 发送MQTT消息
                mqttProducer.send(tidParam.getPtopic(), payload);
                Thread.sleep(1000);
            } catch (Exception e) {
                // 捕获并抛出异常
                throw new RuntimeException(e);
            }
            Integer a=ammeterMapper.selectAmmeterStatus(dbbh);
            if (a==0){
                return true;
            }else {
                return false;
            }
        }else{
            //合闸操作
            byte[] crcHexString = Crc16Utils.getData(tid,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_1,
                    AmmeterMessageConstants.AMMETER_PUBLISH_NULL,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_2,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_4,
                    AmmeterMessageConstants.AMMETER_SWITCH_OPERATION_4);
            log.debug("CRC效验码（十六进制）: {}", crcHexString);
            // 将CRC校验码转换为十六进制字符串并转换为大写
            String finalMessageHex = Crc16Utils.byteTo16String(crcHexString).toUpperCase();
            log.info("最终消息（十六进制）: {}", finalMessageHex);
            try {
                byte[] payload = HexUtils.HexStringToByte(finalMessageHex);
                // 发送MQTT消息
                mqttProducer.send(tidParam.getPtopic(), payload);
                Thread.sleep(1000);
            } catch (Exception e) {
                // 捕获并抛出异常
                throw new RuntimeException(e);
            }
            Integer a=ammeterMapper.selectAmmeterStatus(dbbh);
            if (a==1){
                return true;
            }else {
                return false;
            }
        }
    }

    @Override
    public BigDecimal selectAllPower(String month, String zt, String lc) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        String dbzt=null;
        List<AmmeterResultVO> dbbhs=ammeterMapper.selectAllDbbh(zt,lc,dbzt);
        BigDecimal allpower = BigDecimal.ZERO;
        for(AmmeterResultVO dbbh:dbbhs){
            BigDecimal power = ammeterMapper.selectAllPower(date,dbbh.getDbbh());
            if (power != null) {
                power = power.multiply(dbbh.getMagnification());
                allpower = allpower.add(power);
            }
        }
        return allpower;
    }

    @Override
    public BigDecimal selectTenantPower(String month, String zt, String lc) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        String dbzt="租用";
        List<AmmeterResultVO> dbbhs=ammeterMapper.selectAllDbbh(zt,lc,dbzt);
        BigDecimal TenantPower = BigDecimal.ZERO;
        for(AmmeterResultVO dbbh:dbbhs){
            BigDecimal power = ammeterMapper.selectAllPower(date,dbbh.getDbbh());
            if (power != null) {
                TenantPower = TenantPower.add(power);
            }
        }
        return TenantPower;
    }

    @Override
    public BigDecimal selectPublicPower(String month, String zt, String lc) {
        Date date = DateUtils.getFirstDayOfMonth(month);
        String dbzt="公用";
        List<AmmeterResultVO> dbbhs=ammeterMapper.selectAllDbbh(zt,lc,dbzt);
        BigDecimal publicpower = BigDecimal.ZERO;
        for(AmmeterResultVO dbbh:dbbhs){
            BigDecimal power = ammeterMapper.selectAllPower(date,dbbh.getDbbh());
            if (power!=null){
                power = power.multiply(dbbh.getMagnification());
                publicpower = publicpower.add(power);
            }
        }
        return publicpower;
    }


    /**
     * 选择载体下拉树
     *
     * @param ztParam 查询参数
     * @return 列表树
     */
    @Override
    public List<ZTVO> selectZtTree(ZtParam ztParam) {
        if (ztParam.getLxbh() == 2) {
            return ammeterMapper.selectAllZtzt(ztParam);
        }
        PageHelper.startPage(ztParam.getPageNum(), ztParam.getPageSize());
        return ammeterService.selectzt(ztParam);
    }

    @Override
    public List<ZTVO> selectzt(ZtParam ztParam) {
        log.debug("查询所有载体供添加列表选择");
        if ("1".equals(ztParam.getTgszt())){
            return ammeterMapper.selectzt1(ztParam.getLxbh());
        }
        String[] values = ztParam.getTgszt().split(",");// 按照逗号进行分割
        return ammeterMapper.selectzt(ztParam.getLxbh(),values,ztParam.getNr(),ztParam.getQygs());
    }

    @Override
    public int add(AmmeterParam ammeterParam) {
        log.debug("新增电表: {}",ammeterParam);
        AmmeterAddPO ammeterAddPO=new AmmeterAddPO();
        //归属载体
        ammeterAddPO.setZt(ammeterParam.getNr());
        //楼层
        ammeterAddPO.setLc(ammeterParam.getLc());
        //所在位置
        ammeterAddPO.setLocation(ammeterParam.getLocation());
        //电表用途
        ammeterAddPO.setDbyt(ammeterParam.getDbyt());
        //倍率
        ammeterAddPO.setMagnification(ammeterParam.getMagnification());
        //智联器编号
        ammeterAddPO.setZlid(ammeterParam.getZlid());
        //操作地址
        ammeterAddPO.setTid(ammeterParam.getTid());
        ammeterAddPO.setDbdj(ammeterParam.getDbdj());
        ammeterAddPO.setDbzt("空闲");
        ammeterAddPO.setTjsj(new Date());
        ammeterAddPO.setTname(ammeterParam.getTname());
        ammeterAddPO.setModelId(ammeterParam.getModelId());
        int result= ammeterMapper.add(ammeterAddPO);
        //查找最新的dbid
        int number=ammeterMapper.dbid();
        String formattedNumber = String.format("%03d", number);
        String ztsx=ammeterParam.getNra();
        //电表编号拼接
        ammeterAddPO.setDbbh(ztsx+formattedNumber);
        ammeterAddPO.setDbid(number);
        int i = ammeterMapper.updateAmmeterDbbh(ammeterAddPO);
        //添加进年度电表数据
        AmmeterResultPo ammeterResultPo = new AmmeterResultPo();
        ammeterResultPo.setDbbh(ztsx+formattedNumber);
        ammeterResultPo.setTimestamp(new Date());
        ammeterResultPo.setTotalPower(BigDecimal.ZERO);
        ammeterMapper.insertYear(ammeterResultPo);
        return result;
    }

    @Override
    public List<RoomVO> selectHouse(AmmeterParam ammeterParam) {
        log.debug("通过载体和楼层找房间号");
        List<RoomVO> roomVOS = ammeterMapper.selectHouse(ammeterParam);
        return roomVOS;
    }

    @Override
    public List<EnterpriseVO> enterprise(AmmeterParam ammeterParam) {
        log.debug("通过载体找企业");
        List<EnterpriseVO> enterprise = ammeterMapper.enterprise(ammeterParam);
        return enterprise;
    }

    @Override
    public List<AmmeterResultVO> startDayPower(AmmeterParam ammeterParam) {
        log.debug("通过启动时间找当月电表每天数据");
        String dbbh = ammeterParam.getDbbh();
        Date qysj = ammeterParam.getQysj();
        List<AmmeterResultVO> data = ammeterMapper.startDayPower(dbbh, qysj);
        return data;
    }

    @Transactional
    @Override
    public boolean startAssociation(StartAssociationParam startAssociationParam) {
        log.debug("启动关联电表");
        //租用流程:先去修改电表总表补全信息,添加对应的的租用表信息
        if ("租用".equals(startAssociationParam.getYt())){
            String currentDbbh = startAssociationParam.getDbbh();
            String fjhList = startAssociationParam.getFjh();
            // 构造主表对象
            AmmeterAddPO ammeterAddPO = new AmmeterAddPO();
            ammeterAddPO.setDbbh(currentDbbh);
            ammeterAddPO.setFjh(fjhList); // 多个房间号用逗号拼接
            ammeterAddPO.setQymc(startAssociationParam.getQymc());
            ammeterAddPO.setKhbh(startAssociationParam.getKhbh());
            ammeterAddPO.setDbzt("使用");
            ammeterAddPO.setTname(startAssociationParam.getTname());
            ammeterAddPO.setDbyt(startAssociationParam.getYt());
            ammeterAddPO.setTjsj(new Date());
            ammeterAddPO.setYx(1);
            int a = ammeterMapper.updateAmmeter(ammeterAddPO);
            if (a <= 0) {
                return false;
            }

            // 查询电表信息
            AmmeterAddPO ammeterAddPO1 = ammeterMapper.selectdbbh(currentDbbh);
            if (ammeterAddPO1 == null) {
                return false;
            }

            // 构造明细对象
            QldbzymxPO qldbzymxPO = new QldbzymxPO();
            qldbzymxPO.setDbbh(ammeterAddPO1.getDbbh());
            qldbzymxPO.setDbid(ammeterAddPO1.getDbid());
            qldbzymxPO.setZt(ammeterAddPO1.getZt());
            qldbzymxPO.setFjh(fjhList); // 设置合并后的 fjh
            qldbzymxPO.setQymc(startAssociationParam.getQymc());
            qldbzymxPO.setKhbh(startAssociationParam.getKhbh());
            qldbzymxPO.setDbyt(ammeterAddPO1.getDbyt());
            qldbzymxPO.setZyzt("使用");
            qldbzymxPO.setDbbl(ammeterAddPO1.getMagnification());
            qldbzymxPO.setTname(startAssociationParam.getTname());
            qldbzymxPO.setTjsj(new Date());
            qldbzymxPO.setJfyx(1);
            qldbzymxPO.setYx(1);
            qldbzymxPO.setQysj(startAssociationParam.getQysj());
            qldbzymxPO.setCsdl(startAssociationParam.getCsdl());
            qldbzymxPO.setDfdj(ammeterAddPO1.getDbdj());
            int b = ammeterMapper.insertzymx(qldbzymxPO);

            // 获取并分割 fjhList
            if (fjhList != null && !fjhList.isEmpty()) {
                String[] fjhArray = fjhList.split(",");

                // 遍历数组，逐条更新 stqyy 表
                for (String fjh : fjhArray) {
                    // 去除空格等空白字符
                    String trimmedFjh = fjh.trim();

                    // 构造参数对象或直接传参
                    ammeterMapper.updateSqtyy(trimmedFjh, 1);
                }
            }

            if (b <= 0) {
                return false;
            }
            //查询qldbqyinfo
            QldbqyinfoVO qldbqyinfoVO = ammeterMapper.selectqymx(startAssociationParam.getKhbh());
            if (qldbqyinfoVO==null){
                Qlqyinfo qlqyinfo = new Qlqyinfo();
                qlqyinfo.setKhbh(startAssociationParam.getKhbh());
                qlqyinfo.setQymc(startAssociationParam.getQymc());
                qlqyinfo.setZt(ammeterAddPO1.getZt());
                qlqyinfo.setTname(startAssociationParam.getTname());
                qlqyinfo.setTjsj(new Date());
                int d=ammeterMapper.add3(qlqyinfo);
                if (d<=0){
                    return false;
                }
            }
            //当客户编号一致载体不一致更新载体
            if (qldbqyinfoVO != null && ammeterAddPO1 != null) {
                String zt1 = qldbqyinfoVO.getZt();
                String zt2 = ammeterAddPO1.getZt();

                if (!Objects.equals(zt1, zt2)) {
                    // 示例逻辑：更新载体信息
                    log.info("载体不一致，准备更新载体信息");
                    int z= ammeterMapper.updateqymx(startAssociationParam.getKhbh(),zt2);
                    if (z<=0){
                        return false;
                    }
                }
            }
            return true;

            //自用和公用 只修改电表总表信息
        }else{

            String currentDbbh = startAssociationParam.getDbbh();
            String fjhList =startAssociationParam.getFjh();

            // 构造主表对象
            AmmeterAddPO ammeterAddPO = new AmmeterAddPO();
            ammeterAddPO.setDbbh(currentDbbh);
            ammeterAddPO.setFjh(fjhList); // 多个房间号用逗号拼接
            ammeterAddPO.setQymc(startAssociationParam.getQymc());
            ammeterAddPO.setKhbh(startAssociationParam.getKhbh());
            ammeterAddPO.setDbzt("使用");
            ammeterAddPO.setTname(startAssociationParam.getTname());
            ammeterAddPO.setDbyt(startAssociationParam.getYt());
            ammeterAddPO.setTjsj(new Date());
            ammeterAddPO.setYx(1);

            int a = ammeterMapper.updateAmmeter(ammeterAddPO);
            if (a <= 0) {
                return false;
            }

            return true;
        }
    }

    @Override
    public boolean withdraw(StartAssociationParam startAssociationParam) {
        log.debug("退用关联");
        //通过电表id查询电表下关联房间号信息
        String fjh=ammeterMapper.selectFjh(startAssociationParam.getDbbh());
        // 获取并分割 fjhList
        if (fjh != null && !fjh.isEmpty()) {
            String[] fjhArray = fjh.split(",");

            // 遍历数组，逐条更新 stqyy 表
            for (String fjhItem : fjhArray) {
                // 去除空格等空白字符
                String trimmedFjh =fjhItem.trim();

                // 构造参数对象或直接传参
                ammeterMapper.updateSqtyy(trimmedFjh, 0);
            }
        }
        //清空电表总表
        AmmeterAddPO ammeterAddPO = new AmmeterAddPO();
        ammeterAddPO.setDbbh(startAssociationParam.getDbbh());
        ammeterAddPO.setFjh(null);
        ammeterAddPO.setQymc(null);
        ammeterAddPO.setKhbh(null);
        ammeterAddPO.setDbyt(null);
        ammeterAddPO.setDbzt("空闲");
        ammeterAddPO.setTname(startAssociationParam.getTname());
        ammeterAddPO.setTjsj(new Date());
        ammeterAddPO.setYx(1);
        int a = ammeterMapper.updateAmmeter(ammeterAddPO);
        if (a <= 0) {
            return false;
        }

//        联系人表清空
//        int b=ammeterMapper.updateyh(startAssociationParam.getDbbh());
//        if ( b <=0){
//            return false;
//        }

        //租用表清空
        QldbzymxPO qldbzymxPO = new QldbzymxPO();
        //电表编号
        qldbzymxPO.setDbbh(startAssociationParam.getDbbh());
        //退用时间
        qldbzymxPO.setTysj(startAssociationParam.getTysj());
        //最终电量
        qldbzymxPO.setZzdl(startAssociationParam.getZzdl());
        //操作时间
        qldbzymxPO.setTname(startAssociationParam.getTname());
        qldbzymxPO.setTjsj(new Date());
        qldbzymxPO.setZyzt("已退用");
        qldbzymxPO.setJfyx(0);
        qldbzymxPO.setYx(1);
        int c = ammeterMapper.updatezymx(qldbzymxPO);
        if (c <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public List<AmmeterResultVO> freeListFilter(AmmeterParam ammeterParam) {
        log.debug("显示空闲列表筛选");

        // 当前账号非admin账号
        if (StringUtils.isNotBlank(ammeterParam.getTgszt()) && !"1".equals(ammeterParam.getTgszt())) {
            ZtParam ztParam = new ZtParam();
            ztParam.setTgszt(ammeterParam.getTgszt());
            List<ZTVO> ztvos = ammeterMapper.selectZtByNra(ztParam);
            if (CollectionUtils.isNotEmpty(ztvos)) {
                ammeterParam.setZt(ztvos.get(0).getNr());
            }
        }
        PageHelper.startPage(ammeterParam.getPageNum(), ammeterParam.getPageSize());
        List<AmmeterResultVO> ammeterResultVOS = ammeterMapper.selectFreeFileter(ammeterParam);
        return ammeterResultVOS;
    }

    @Override
    public List<AmmeterResultVO> useListFilter(AmmeterParam ammeterParam) {
        log.debug("查询使用电表");
        // 当前账号非admin账号
        if (StringUtils.isNotBlank(ammeterParam.getTgszt()) && !"1".equals(ammeterParam.getTgszt())) {
            ZtParam ztParam = new ZtParam();
            ztParam.setTgszt(ammeterParam.getTgszt());
            List<ZTVO> ztvos = ammeterMapper.selectZtByNra(ztParam);
            if (CollectionUtils.isNotEmpty(ztvos)) {
                ammeterParam.setZt(ztvos.get(0).getNr());
            }
        }

        PageHelper.startPage(ammeterParam.getPageNum(), ammeterParam.getPageSize());
        List<AmmeterResultVO> ammeterResultVOS = ammeterMapper.selectUseFileter(ammeterParam);
        return ammeterResultVOS;
    }

    @Override
    public List<AmmeterResultVO> updateRoom(AmmeterParam ammeterParam) {
        log.debug("显示客户关联的电表信息");
        return ammeterMapper.updateRoom(ammeterParam);
    }
    @Override
    public List<AmmeterResultVO> stqyyData(AmmeterParam ammeterParam) {
        log.debug("显示电表关联的房源信息");
        List<AmmeterResultVO> ammeterResultVOS=ammeterMapper.stqyyData(ammeterParam);
        return ammeterResultVOS;
    }

    @Override
    public int updateRoomAa(AmmeterParam ammeterParam) {
        log.debug("更新电表关联的房源信息");
        //更新房源表信息
        //通过电表id查询电表下关联房间号信息
        String fjh=ammeterMapper.selectFjh1(ammeterParam.getDbid());
        // 获取并分割 fjhList
        if (fjh != null && !fjh.isEmpty()) {
            String[] fjhArray = fjh.split(",");

            // 遍历数组，逐条更新 stqyy 表
            for (String fjhItem : fjhArray) {
                // 去除空格等空白字符
                String trimmedFjh =fjhItem.trim();

                // 构造参数对象或直接传参
                ammeterMapper.updateSqtyy(trimmedFjh, 0);
            }
        }
        //通过电表id查询电表下关联房间号信息
        String fjh1 = ammeterParam.getFjh();
        // 获取并分割 fjhList
        if (fjh1 != null && !fjh1.isEmpty()) {
            String[] fjhArray = fjh1.split(",");

            // 遍历数组，逐条更新 stqyy 表
            for (String fjhItem1 : fjhArray) {
                // 去除空格等空白字符
                String trimmedFjh =fjhItem1.trim();

                // 构造参数对象或直接传参
                ammeterMapper.updateSqtyy(trimmedFjh, 1);
            }
        }
        //更新房源信息
        AmmeterAddPO ammeterAddPO = new AmmeterAddPO();
        ammeterAddPO.setDbid(ammeterParam.getDbid());
        ammeterAddPO.setFjh(ammeterParam.getFjh());
        int i = ammeterMapper.updateRoomAa(ammeterAddPO);
        //更新租用表房源信息
        QldbzymxPO qldbzymxPO = new QldbzymxPO();
        qldbzymxPO.setDbid(ammeterParam.getDbid());
        qldbzymxPO.setFjh(ammeterParam.getFjh());
        int j = ammeterMapper.updatezymx1(qldbzymxPO);
        if (i<=0){
            return 0;
        }
        if (j<=0){
            return 0;
        }
        return 1;
    }


}
